/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package CL;

import EL.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import slsBeans.RoomBLORemote;
import slsBeans.TableBLORemote;
import slsBeans.TableTypeBLORemote;

/**
 *
 * @author Tian
 */
public class TableCO extends HttpServlet {
   
    private TableBLORemote rTable;
    private TableTypeBLORemote rTableType;
    private RoomBLORemote rRoom;

    @Override
    public void init() throws ServletException
    {
        try
        {
            super.init();
            String jndiFileName = this.getServletContext().getRealPath("/") + "/WEB-INF/jndi.properties";
            Properties props = new Properties();
            props.load(new FileInputStream(jndiFileName));
            InitialContext ctx = new InitialContext(props);
            rTable = (TableBLORemote) ctx.lookup("TableBLO/remote");
            rRoom = (RoomBLORemote) ctx.lookup("RoomBLO/remote");
            rTableType = (TableTypeBLORemote) ctx.lookup("TableTypeBLO/remote");
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String action = request.getParameter("action");
        if (action.equalsIgnoreCase("getAll"))
        {
            List<RestaurantTables> tables = rTable.getAll();

            request.setAttribute("tables", tables);
            RequestDispatcher rd = request.getRequestDispatcher("ad_Table_Viewing.jsp");
            rd.forward(request, response);
        }
        else if (action.equalsIgnoreCase("formAddNew"))
        {
            List<TableTypes> tableTypes = rTableType.getAll();
            List<DiningRooms> rooms = rRoom.getAll();
            request.setAttribute("tableTypes", tableTypes);
            request.setAttribute("rooms", rooms);
            RequestDispatcher rd = request.getRequestDispatcher("ad_Table_Adding.jsp");
            rd.forward(request, response);
        }
        else if (action.equalsIgnoreCase("add"))
        {
            if (ServletFileUpload.isMultipartContent(request))
            {
                ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
                List items = null;
                try
                {
                    items = upload.parseRequest(request);
                }
                catch (Exception ex)
                {
                    ex.printStackTrace();
                }

                String imgPath = "";
                Hashtable params = new Hashtable();
                Iterator iter = items.iterator();
                while (iter.hasNext())
                {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField())
                    {
                        params.put(item.getFieldName(), item.getString());
                    }
                    else
                    {
                        String fileName = item.getName();
                        fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
                        imgPath = "images/" + fileName;
                        String realPath = this.getServletContext().getRealPath("/") + imgPath;
                        File fileUpload = new File(realPath);
                        try
                        {
                            item.write(fileUpload);
                        }
                        catch (Exception ex)
                        {
                            ex.printStackTrace();
                        }
                    }
                }

                String tableTypeID = (String) params.get("cbbTableType");

                String roomID = (String) params.get("cbbRoom");


                TableTypes tbt = rTableType.getByID(Integer.parseInt(tableTypeID));
                DiningRooms room = rRoom.getByID(Integer.parseInt(roomID));

                RestaurantTables t = new RestaurantTables(imgPath);

                boolean result = rTable.add(t,tbt,room);
                if (result)
                {
                    response.sendRedirect("TableCO?action=getAll");
                }
                else
                {
                    response.sendRedirect("TableCO?action=formAddNew");
                }
            }
        }
        else if(action.equalsIgnoreCase("formEditImage"))
        {
            String id = request.getParameter("id");
            RestaurantTables table = rTable.getByID(Integer.parseInt(id));
            request.setAttribute("table", table);
            RequestDispatcher rd = request.getRequestDispatcher("ad_Table_ImageEditing.jsp");
            rd.forward(request, response);
        }
        else if (action.equalsIgnoreCase("editImage"))
        {

            if (ServletFileUpload.isMultipartContent(request))
            {
                ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
                List items = null;
                try
                {
                    items = upload.parseRequest(request);
                }
                catch (Exception ex)
                {
                    ex.printStackTrace();
                }

                String imgPath = "";
                Hashtable params = new Hashtable();
                Iterator iter = items.iterator();
                while (iter.hasNext())
                {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField())
                    {
                        params.put(item.getFieldName(), item.getString());
                    }
                    else
                    {
                        String fileName = item.getName();
                        fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
                        imgPath = "images/" + fileName;
                        String realPath = this.getServletContext().getRealPath("/") + imgPath;
                        File fileUpload = new File(realPath);

                        try
                        {
                            item.write(fileUpload);

                        }
                        catch (Exception ex)
                        {
                            ex.printStackTrace();
                        }
                    }
                }
                String id = (String) params.get("txtID");
                RestaurantTables table = rTable.getByID(Integer.parseInt(id));
                if (table != null)
                {
                    table.setImgPath(imgPath);
                    boolean result = rTable.edit(table);
                    if (result)
                    {
                        response.sendRedirect("TableCO?action=getAll");
                    }
                    else
                    {
                        response.sendRedirect("TableCO?action=formEditImage");
                    }
                }
            }
        }
        else if (action.equalsIgnoreCase("delete"))
        {
            String id = request.getParameter("id");
            boolean result = rTable.delete(Integer.parseInt(id));
            if (result)
            {
                response.sendRedirect("TableCO?action=getAll");
            }
            else
            {
                response.sendRedirect("TableCO?action=getAll");
            }
        }
        else if(action.equalsIgnoreCase("viewTable"))
        {
            String id = request.getParameter("id");
            DiningRooms room = rRoom.getByID(Integer.parseInt(id));
            List<RestaurantTables> tables = room.getTablesList();
            request.setAttribute("tables", tables);
            HttpSession session = request.getSession(true);
            session.setAttribute("room", room);
            RequestDispatcher rd = request.getRequestDispatcher("us_ViewTable.jsp");
            rd.forward(request, response);
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
